﻿Type.registerNamespace('MS.InformationManagement.Ribbon.DocumentScheduler');
MS.InformationManagement.Ribbon.DocumentScheduler.ActionsEnum = {
    Schedule: 0,
    Unschedule: 1
}

MS.InformationManagement.Ribbon.DocumentScheduler.TooltipMetadataTemplate = '<p><b>Remitente / Destinatario:</b> {REMITENTE}</p><p><b>Palabras Clave:</b> {PALABRAS}</p><p><b>Asunto:</b> {ASUNTO}</p>';

MS.InformationManagement.Ribbon.DocumentScheduler.OnDialogClose = function (dialogResult, returnValue) {
    switch (dialogResult) {
        case SP.UI.DialogResult.cancel:
        case SP.UI.DialogResult.OK:
        default:
            window.location.href = window.location.href;
            break;
    }
}

MS.InformationManagement.Ribbon.DocumentScheduler.OpenSchedulerModal = function (siteUrl, libraryGuid, queryString, action) {
    var modalOptions = {
        title: '',
        url: siteUrl + '/_layouts/MS.InformationManagement.WP/DocumentScheduler.aspx?libraryID=' + libraryGuid,
        allowMaximize: false,
        showClose: true,
        autoSize: true,
        dialogReturnValueCallback: MS.InformationManagement.Ribbon.DocumentScheduler.OnDialogClose
    };
    if (queryString) {
        switch (action) {
            case MS.InformationManagement.Ribbon.DocumentScheduler.ActionsEnum.Schedule:
                modalOptions.title = 'Agendar Documentos';
                break;
            case MS.InformationManagement.Ribbon.DocumentScheduler.ActionsEnum.Unschedule:
                modalOptions.title = 'Desagendar Documentos';
                break;
        }
        modalOptions.url = modalOptions.url + queryString + '&action=' + action;
    }
    else { modalOptions.title = "Ver Estado de la agenda documental"; }

    SP.UI.ModalDialog.showModalDialog(modalOptions);
}

MS.InformationManagement.Ribbon.DocumentScheduler.ScheduleDocuments = function (siteUrl, libraryGuid) {
    var queryString = MS.InformationManagement.Ribbon.GetItemsIDQueryString();
    if (queryString !== '') {
        MS.InformationManagement.Ribbon.DocumentScheduler.OpenSchedulerModal(
		siteUrl
		, libraryGuid
		, queryString
		, MS.InformationManagement.Ribbon.DocumentScheduler.ActionsEnum.Schedule);
    }
    else { MS.InformationManagement.Common.ShowStatus('Debe seleccionar al menos un documento para ser agendado.', 'yellow', 6000); }
}

MS.InformationManagement.Ribbon.DocumentScheduler.UnScheduleDocuments = function (siteUrl, libraryGuid) {
    var queryString = MS.InformationManagement.Ribbon.GetItemsIDQueryString();
    if (queryString) {
        MS.InformationManagement.Ribbon.DocumentScheduler.OpenSchedulerModal(
			siteUrl
			, libraryGuid
			, queryString
			, MS.InformationManagement.Ribbon.DocumentScheduler.ActionsEnum.Unschedule);
    }
    else { MS.InformationManagement.Common.ShowStatus('Debe seleccionar al menos un documento para ser agendado.', 'yellow', 6000); }
}

MS.InformationManagement.Ribbon.DocumentScheduler.OnScheduleSuccess = function (result, userState) {
    $('#wrap').ajaxloader('hide');
    MS.InformationManagement.Common.ShowStatus('El documento ' + userState.DocumentTitle + ' ha sido agendado exitosamente.', 'green', 6000);
}

MS.InformationManagement.Ribbon.DocumentScheduler.OnUnScheduleSuccess = function (result, userState) {
    $('#wrap').ajaxloader('hide');
    MS.InformationManagement.Common.ShowStatus('Ha cancelado el agendado para el documento ' + userState.DocumentTitle, 'green', 6000);
    setTimeout(function () {
        $(userState.Calendar).fullCalendar('removeEvents', userState.eventID)
    }, 550);
}

MS.InformationManagement.Ribbon.DocumentScheduler.OnAjaxCallFailed = function (exception, userState) {
    $('#wrap').ajaxloader('hide');
    MS.InformationManagement.Common.ShowStatus('Ha ocurrido una excepción mientras se procesaba su peticion: ' + exception.get_message(), 'red', 6000);
}

MS.InformationManagement.Ribbon.DocumentScheduler.OnDocumentFetchComplete = function (result, userstate) {
    var metadatatooltip = userstate.tooltip;
    metadatatooltip.qtip('option', {
        'content.title.text': 'Datos del Radicado ' + result.Name,
        'content.text': MS.InformationManagement.Ribbon.DocumentScheduler.TooltipMetadataTemplate.replace('{REMITENTE}', result.FromTo).replace('{ASUNTO}', result.Subject).replace('{PALABRAS}', result.Keywords)
    });
}

MS.InformationManagement.Ribbon.DocumentScheduler.Initialize = function (siteUrl, reciclebinElementID, userLibraryGuid) {
    var calendar = null;
    var recycleBin = null;
    $('#wrap').ajaxloader({ fullscreen: true, baseurl: siteUrl, autoshow: false });
    MS.InformationManagement.Services.DocumentSchedulerService.set_path(siteUrl + MS.InformationManagement.Services.DocumentSchedulerService.get_path());

    /* initialize the external events
    -----------------------------------------------------------------*/
    recycleBin = $('#' + reciclebinElementID).droppable(
		{
		    activeClass: 'ui-state-active ui-corner-all',
		    drop: function (event, ui) {
		        var calendarEvent = $(this).data('eventObject');
		        if (calendarEvent && calendarEvent != null) {
		            $('#wrap').ajaxloader('show');
		            var userState = {
		                notificationID: MS.InformationManagement.Common.ShowLoadingNotification('Por favor espere...'),
		                DocumentTitle: calendarEvent.title,
		                Calendar: calendar,
		                eventID: calendarEvent.id
		            };
		            MS.InformationManagement.Services.DocumentSchedulerService.UnscheduleDocument(
					calendarEvent.library,
					calendarEvent.id,
					MS.InformationManagement.Ribbon.DocumentScheduler.OnUnScheduleSuccess,
					MS.InformationManagement.Ribbon.DocumentScheduler.OnAjaxCallFailed,
					userState);
		        } else {
		            MS.InformationManagement.Common.ShowStatus('No puede desagendar un documento que aun no ha sido agendado.', 'yellow', 6000);
		        }
		    }
		}
	);
    $('#external-events div.external-event').each(function () {

        // create an Event Object (http://arshaw.com/fullcalendar/docs/event_data/Event_Object/)
        // it doesn't need to have a start or end
        var eventObject = {
            id: $.trim($(this).find('input')[0].value),
            dueDate: $.trim($(this).find('input')[1].value) === '' ? 'undefined' : new Date($.trim($(this).find('input')[1].value)),
            title: $.trim($(this).find('span').text()) // use the element's text as the event title
        };

        // store the Event Object in the DOM element so we can get to it later
        $(this).data('eventObject', eventObject);

        // make the event draggable using jQuery UI
        $(this).draggable({
            zIndex: 999,
            revert: true,      // will cause the event to go back to its
            revertDuration: 0  //  original position after the drag
        });

    });


    /* initialize the calendar
    -----------------------------------------------------------------*/
    calendar = $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month'
        },
        buttonText: {
            today: 'Hoy',
            month: 'Vista Mensual'
        },
        monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
        monthNamesShort: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dic'],
        dayNames: ['Domingo', 'Lunes', 'Martes', 'Mi&eacute;rcoles', 'Jueves', 'Viernes', 'S&aacute;bado'],
        dayNamesShort: ['Dom', 'Lun', 'Mar', 'Mi&eacute;', 'Jue', 'Vie', 'S&aacute;b'],
        editable: true,
        droppable: true, // this allows things to be dropped onto the calendar !!!
        drop: function (date, allDay) { // this function is called when something is dropped

            var currentDayOfWeek = date.getDay();
            var currentTime = new Date();
            currentTime.setHours(0, 0, 0, 0);
            if (currentDayOfWeek === 0 || currentDayOfWeek === 6) {
                MS.InformationManagement.Common.ShowStatus('No es válido agendar documentos para días no hábiles.', 'yellow', 6000);
                return;
            }
            if (date < currentTime) {
                MS.InformationManagement.Common.ShowStatus('No es posible agendar documentos en una fecha inferior a la fecha actual.', 'yellow', 6000);
                return;
            }
            // retrieve the dropped element's stored Event Object
            var originalEventObject = $(this).data('eventObject');
            if (typeof originalEventObject.dueDate != 'string' && originalEventObject.dueDate) { originalEventObject.dueDate.setHours(0, 0, 0, 0); }
            if (originalEventObject.dueDate && typeof originalEventObject.dueDate != 'string' && date >= originalEventObject.dueDate) {
                MS.InformationManagement.Common.ShowStatus('No es permitido agendar un documentos con fecha superior o igual a la fecha máxima de atención del documento.', 'yellow', 6000);
                //revertFunc();
                return;
            }
            $('#wrap').ajaxloader('show');
            if (MS.InformationManagement.Common.IsHoliday(date) === false) {
                $('#wrap').ajaxloader('hide');
                MS.InformationManagement.Common.ShowStatus('No es válido agendar documentos para días no hábiles.', 'yellow', 6000);
                return;
            }
            var userState = {
                DocumentTitle: originalEventObject.title
            };
            MS.InformationManagement.Services.DocumentSchedulerService.ScheduleDocument(
					userLibraryGuid,
					originalEventObject.id,
					date,
					MS.InformationManagement.Ribbon.DocumentScheduler.OnScheduleSuccess,
					MS.InformationManagement.Ribbon.DocumentScheduler.OnAjaxCallFailed,
					userState
				);
            // we need to copy it, so that multiple events don't have a reference to the same object
            var copiedEventObject = $.extend({}, originalEventObject);

            // assign it the date that was reported
            copiedEventObject.start = date;
            copiedEventObject.allDay = allDay;

            // render the event on the calendar
            // the last `true` argument determines if the event "sticks" (http://arshaw.com/fullcalendar/docs/event_rendering/renderEvent/)
            $('#calendar').fullCalendar('renderEvent', copiedEventObject, false);

            $(this).remove();

        },
        eventDrop: function (event, dayDelta, minuteDelta, allDay, revertFunc) {

            var currentDayOfWeek = event._start.getDay();
            var currentTime = new Date();
            currentTime.setHours(0, 0, 0, 0);
            if (currentDayOfWeek === 0 || currentDayOfWeek === 6) {
                MS.InformationManagement.Common.ShowStatus('No es válido agendar documentos para días no hábiles.', 'yellow', 6000);
                revertFunc();
                return;
            }
            if (event._start < currentTime) {
                MS.InformationManagement.Common.ShowStatus('No es posible agendar documentos en una fecha inferior a la fecha actual.', 'yellow', 6000);
                revertFunc();
                return;
            }
            if (event.dueDate && typeof event.dueDate != 'string') { event.dueDate.setHours(0, 0, 0, 0); }
            if (event.dueDate && typeof event.dueDate != 'string' && event._start >= event.dueDate) {
                MS.InformationManagement.Common.ShowStatus('No es permitido agendar un documentos con fecha superior a la fecha máxima de atención del documento.', 'yellow', 6000);
                revertFunc();
                return;
            }
            $('#wrap').ajaxloader('show');
            if (MS.InformationManagement.Common.IsHoliday(event._start) === false) {
                $('#wrap').ajaxloader('hide');
                MS.InformationManagement.Common.ShowStatus('No es válido agendar documentos para días no hábiles.', 'yellow', 6000);
                revertFunc();
                return;
            }
            var userState = {
                DocumentTitle: event.title
            };
            MS.InformationManagement.Services.DocumentSchedulerService.ScheduleDocument(
					userLibraryGuid,
					event.id,
					event._start,
					MS.InformationManagement.Ribbon.DocumentScheduler.OnScheduleSuccess,
					MS.InformationManagement.Ribbon.DocumentScheduler.OnAjaxCallFailed,
					userState
				);
        },
        eventDragStart: function (event, jsEvent, ui, view) {
            recycleBin.data('eventObject', event);
        },
        eventDragStop: function (event, jsEvent, ui, view) {
            recycleBin.data('eventObject', null);
        },
        eventSources: [
			function (start, end, callback) {
			    $('.fc-day-holiday').removeClass('fc-day-holiday');
			    var holidaysArray = MS.InformationManagement.Common.FetchHolidays(start, end);
			    if (typeof holidaysArray != 'undefined' && holidaysArray != null)
			        for (var dayIndex = 0; dayIndex < 42; dayIndex++) {
			            var currentDate = new Date(start);
			            currentDate.setDate(currentDate.getDate() + dayIndex);
			            currentDate.setHours(0, 0, 0, 0);
			            for (var arrayIndex = 0; arrayIndex < holidaysArray.length; arrayIndex++) {
			                var currentHoliday = holidaysArray[arrayIndex];
			                var holidayDate = new Date(parseInt(/\/Date\((\d+).*/.exec(currentHoliday.DateTime)[1]));
			                holidayDate.setHours(0, 0, 0, 0);
			                if (currentDate.toString() === holidayDate.toString()) {
			                    var selector = '.fc-day' + dayIndex;
			                    $(selector).addClass('fc-day-holiday')
			                }
			            }
			        }
			    MS.InformationManagement.Services.DocumentSchedulerService.FetchDocuments(
					start,
					end,
					userLibraryGuid,
					function (result) {
					    var events = [];
					    for (var i in result) {
					        events.push(
								{
								    title: result[i].Name,
								    id: result[i].ID,
								    start: result[i].ScheduleDate,
								    dueDate: result[i].DueDate,
								    allday: true,
								    color: '#309dcf',
								    library: result[i].Library
								}
							);
					    }
					    callback(events);
					},
					MS.InformationManagement.Ribbon.DocumentScheduler.OnAjaxCallFailed
				);
			},
			function (start, end, callback) {
			    MS.InformationManagement.Services.DocumentSchedulerService.FetchUnansweredDocuments(
					start,
					end,
					userLibraryGuid,
					function (result) {
					    var events = [];
					    for (var i in result) {
					        events.push(
								{
								    auxid: result[i].ID,
								    title: result[i].Name,
								    start: result[i].DueDate,
								    allday: true,
								    color: '#c60e05',
								    editable: false,
								    library: result[i].Library
								}
							);
					    }
					    callback(events);
					},
					MS.InformationManagement.Ribbon.DocumentScheduler.OnAjaxCallFailed
				);
			} ],
        loading: function (isLoading, view) {
            if (isLoading === true) {
                $('#wrap').ajaxloader('show');
            }
            else { $('#wrap').ajaxloader('hide'); }
        },
        eventMouseover: function (event, jsEvent, view) {
            var id = typeof event.id == 'undefined' ? event.auxid : event.id;
            var library = event.library;
            var metadataTooltip = $(this).qtip(
				{
				    content: {
				        title: 'Cargando, por favor espere...',
				        text: '<img src="/_layouts/images/MS.InformationManagement.Branding/preloader_small.gif" style="display:block; margin: 0 auto;"/>'
				    },
				    hide: {
				        event: 'unfocus mouseleave'
				    },
				    style: { widget: true },
				    position: {
				        my: 'top center'
				    }
				}
			);
            metadataTooltip.qtip('show');
            MS.InformationManagement.Services.DocumentSchedulerService.GetDocument(
				library,
				id,
				MS.InformationManagement.Ribbon.DocumentScheduler.OnDocumentFetchComplete,
				function (exception, userstate) { },
				{ tooltip: metadataTooltip }
			);
        }
    });
}